﻿#include "StrategyOptionUI.h"
#include <QFileDialog>
#include "OptionManager.h"
#include "StrategyDelegate.h"

StrategyOptionUI::StrategyOptionUI(const QStringList &pSymbolList, QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	initUI(pSymbolList);
}

StrategyOptionUI::~StrategyOptionUI()
{
}

void StrategyOptionUI::saveOption()
{
	for (int i = 0; i < ui.tablist_symbols->rowCount(); ++i)
	{
		QString symbolName = ui.tablist_symbols->item(i, 0)->text();
		QString strategyName = ui.tablist_symbols->item(i, 1)->text();
		if (strategyName.isEmpty())
		{
			continue;
		}
		if (symbolName.compare(QString::fromLocal8Bit("DefaultSymbol")) == 0) // 默认合约
		{
			m_manager.SetDefaultStrategy(strategyName.toLocal8Bit().data());
		}
		else
		{
			m_manager.SetStrategy(symbolName.toLocal8Bit().data(), strategyName.toLocal8Bit().data());
		}
	}
	m_manager.SaveStrategy();
}

void StrategyOptionUI::initUI(const QStringList &pSymbolList)
{
	ui.tablist_symbols->setRowCount(pSymbolList.size() + 1);
	// 添加默认合约
	{
		QTableWidgetItem *nameItem = new QTableWidgetItem(QString::fromLocal8Bit("DefaultSymbol"));
		ui.tablist_symbols->setItem(0, 0, nameItem);
		std::string defaultStrategy = m_manager.GetDefaultStrategy();
		QTableWidgetItem *strategyItem = new QTableWidgetItem(QString::fromLocal8Bit(defaultStrategy.c_str()));
		ui.tablist_symbols->setItem(0, 1, strategyItem);
	}
	int pRow = 1;
	for (QStringList::ConstIterator itSymbol = pSymbolList.begin(); itSymbol != pSymbolList.end(); ++itSymbol, ++pRow)
	{
		QString symbolName = *itSymbol;
		QTableWidgetItem *nameItem = new QTableWidgetItem(symbolName);
		//nameItem->setText(symbolName);
		ui.tablist_symbols->setItem(pRow, 0, nameItem);
		QString strategyName = getStrategyName(*itSymbol);
		QTableWidgetItem *strategyItem = new QTableWidgetItem(strategyName);
		ui.tablist_symbols->setItem(pRow, 1, strategyItem);
	}
	QStringList pStrategyList;
	getAllStrategies(pStrategyList);
	ui.tablist_symbols->setItemDelegateForColumn(1, new StrategyDelegate(pStrategyList, this));//添加QCombox代理
}

QString StrategyOptionUI::getStrategyName(const QString &pSymbolName)
{
	std::string strategyName = m_manager.GetStrategyName(pSymbolName.toLocal8Bit().data());
	return QString::fromLocal8Bit(strategyName.c_str());
}

void StrategyOptionUI::getAllStrategies(QStringList &outList)
{
	std::string stdStrategyDir = OptionManager::Instance().GetStrategyDir();
	QDir dir(QString::fromLocal8Bit(stdStrategyDir.c_str()));
	//要判断路径是否存在
	if (!dir.exists())
	{
		return;
	}
	dir.setFilter(QDir::Files);//实现对文件的过滤

	QFileInfoList list = dir.entryInfoList();
	QStringList string_list;

	for (int i = 0; i < list.size(); ++i)
	{
		QFileInfo fileInfo = list.at(i);
		QString pSuf = fileInfo.suffix();
		if (pSuf.endsWith("json"))
		{
			continue;
		}
		outList << fileInfo.baseName();
	}
}
